package controllers

import (
	"fmt"
	"gindemo02/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

type AccountController struct {
	BaseController
}

func (con AccountController) Index(c *gin.Context) {
	accountList := []models.Account{}

	models.DB.Find(&accountList)

	c.JSON(200, gin.H{
		"result": accountList,
	})
}
func (con AccountController) Detail(c *gin.Context) {
	// 在处理程序中使用c.Get获取值
	if userId, exists := c.Get("userId"); exists {

		userIdInt64, err := ConvertToInt64(userId)
		if err != nil {
			fmt.Println("Error:", err)
			return
		}

		var account models.Account
		result := models.DB.First(&account, userIdInt64) // 1 is the ID you want to query

		if result.Error != nil {
			c.JSON(http.StatusOK, gin.H{"code": 40110, "msg": "找不到用户信息"})
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "succeed", "data": account})
	}
}

func (con AccountController) Edit(c *gin.Context) {
	c.String(http.StatusOK, "-Edit---文章---")
}

func (con AccountController) Search(c *gin.Context) {
	// 获取查询参数
	keyword := c.Query("keyword")

	fmt.Println("我的几", keyword)

	// 创建数据库连接
	db := models.DB

	// 创建查询条件
	condition := fmt.Sprintf("username = '%s' OR mobile = '%s'", keyword, keyword)

	// 查询账号列表
	var accounts []models.Account
	err := db.Where(condition).Find(&accounts).Error
	if err != nil {
		// 处理查询错误
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	// 返回查询结果
	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "succeed", "data": accounts})
}
